package com.huatai.bpmn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.bpmn.entity.TbUserDeploymentEntity;
import com.huatai.bpmn.entity.dto.PageDto;
import com.huatai.bpmn.entity.vo.DeploymentVO;
import com.huatai.bpmn.service.TbBusinessService;
import com.huatai.bpmn.service.TbUserDeploymentService;
import com.huatai.bpmn.mapper.TbUserDeploymentMapper;
import com.huatai.common.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class TbUserDeploymentServiceImpl extends ServiceImpl<TbUserDeploymentMapper, TbUserDeploymentEntity> implements TbUserDeploymentService{

	@Autowired
	private TbBusinessService tbBusinessService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void bindAttentionDeploy(TbUserDeploymentEntity userDeploymentEntity) {
		Long userId = userDeploymentEntity.getUserId();
		List<TbUserDeploymentEntity> userDeploymentList = userDeploymentEntity.getUserDeploymentList();
		LambdaQueryWrapper<TbUserDeploymentEntity> removeUserWrapper = Wrappers.lambdaQuery();
		removeUserWrapper
			.eq(TbUserDeploymentEntity::getUserId,userId);
		remove(removeUserWrapper);
		saveBatch(userDeploymentList);
	}

	@Override
	public List<TbUserDeploymentEntity> getUserDeployList(Long userId) {
		LambdaQueryWrapper<TbUserDeploymentEntity> userDeploymentEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
		userDeploymentEntityLambdaQueryWrapper
			.eq(TbUserDeploymentEntity::getUserId,userId);
		List<TbUserDeploymentEntity> mappingList = list(userDeploymentEntityLambdaQueryWrapper);
		PageDto pageDto = new PageDto();
		pageDto.setPage(0);
		pageDto.setLimit(0);
		R<Map<String, Object>> deployList = tbBusinessService.getDeployList(pageDto);
		Map<String, Object> data = deployList.getData();
		Object deploymentList = data.get("deploymentList");
		if (deploymentList != null){
			for(DeploymentVO deployment : (List<DeploymentVO>)deploymentList){
				for (TbUserDeploymentEntity tbUserDeploymentEntity : mappingList) {
					if (deployment.getDefinitionKey().equals(tbUserDeploymentEntity.getDeployKey())){
						tbUserDeploymentEntity.setDeployName(deployment.getDeployName());
						break;
					}
				}
			}
		}
		return mappingList;
	}
}




